import { decryptByDESModeEBC, encryptByDESModeEBC } from '@/common/encrypt';
import http from '@/common/http';
import { Dialog, Toast } from 'mand-mobile';
import Loading from '@/components/loading';

function pySegSort(arr) {
  var letters = '*ABCDEFGHJKLMNOPQRSTWXYZ'.split('');
  var zh = '阿吧嚓哒妸发旮哈讥咔垃妈拏噢妑七呥扨它穵夕丫帀'.split('');
  var segs = [];
  var curr;
  letters.forEach(function(item, i) {
    curr = {
      letter: item,
      data: []
    };
    arr.forEach(function(obj) {
      let item2 = obj.cityName;
      obj.city = obj.cityName;
      let p = pinyinUtil.getFirstLetter(item2[0]);
      if (item === p) {
        curr.data.push(obj);
      }
    });
    if (curr.data.length) {
      segs.push(curr);
    }
  });
  return segs;
}
const defaultState = () => {
  return {
    incityStatus: 0,
    incityOrderStatus: 0,
    incityInfo: null,
    incityOrderInfo: null,
    incityNearDrivers: [],
    incityStartPosition: null,
    incityEndPosition: null,
    incityDoOrderInfo: null,
    carSiteInfo: null,
    incityCallCarInfo: null,
    carpoolingNumber: null,
    incityHistoryAddress: null,
    orderMoney: null,
    carType: null,
    incityRedMoney: null,
    incityTime: null,
    taxiTravelType: null,
    incitySubmitPaymentInfo: null,
    incityCityList: null,
    incitySortedCityList: null,
    orderWayPath: []
  };
};
const state = defaultState();
const actions = {
  getIncityInfoByCoord(context, coord) {
    return new Promise((resolve, reject) => {
      Loading.show();
      let lnglatStr = coord.join(',');
      let params = {
        lnglat: encryptByDESModeEBC(lnglatStr)
      };
      http.post('/pakj/city/getCityAndCheck', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setIncityInfo', res.data.data);
          resolve();
        } else if (res.data.code === '600001') {
          reject(new Error(res.data.code + ',' + res.data.msg));
        } else if (res.data.code === '000001') {
          reject(new Error(res.data.code + ',' + res.data.msg));
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  checkInityEndPosition(context, params) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('/pakj/city/getCityAndCheck', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          resolve();
        } else if (res.data.code === '600001') {
          reject(new Error(res.data.msg));
        } else if (res.data.code === '000001') {
          reject(new Error(res.data.msg));
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  getIncityDoOrder(context, params) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('/pakj/city/getDoOrder', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setDoOrderInfo', res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  // 拼车时人数
  getIncityCarSite(context) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('/pakj/city/getCarSite', {}).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setCarSiteInfo', res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  // 确认叫车
  incityCallCar(context, params) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('pakj/city/createCityOrder', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setIncityCallCarInfo', res.data.data);
          resolve();
        } else if (res.data.code === '700002') {
          // 取消次数已用完
          reject(new Error(res.data.code + ':' + res.data.msg));
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  /**
   * 获取市内出行历史位置列表
   */
  getIncityHistoryAddress(context, cityId) {
    return new Promise((resolve, reject) => {
      Loading.show();
      let params = {
        cityId: cityId
      };
      http.post('/pakj/city/getHisAddress', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setIncityHistoryAdress', res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  // 支付
  incitySubmitPayment(context, param) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('/pakj/city/payCityOrder', param).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setIncitySubmitPayment', res.data.data);
          resolve();
        } else if (res.data.code === '200008') {
          Dialog.alert({
            title: '错误',
            content: '请不要重复支付',
            onConfirm: () => {
              reject(new Error('200008'));
            }
          });
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  // 订单详情
  getIncityOrderInfo(context, param) {
    return new Promise((resolve, reject) => {
      http.post('/pakj/city/getCityOrderInfo', param).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setIncityOrderInfo', res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  /**
   * 获取市内用车可用城市列表
   */
  getIncityCityList(context) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('/pakj/city/getOpenCityList', '').then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setIncityCityList', res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  /**
   * 通过城市ID获取城市信息
   */
  getIncityCityInfoById(context, cityid) {
    return new Promise((resolve, reject) => {
      Loading.show();
      let params = {
        cityId: cityid
      };
      http.post('/pakj/city/getCityById', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          resolve(res.data.data);
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  },
  // 查询支付状态
  getOrderPayStatus(context, orderno) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http
        .post('pakj/city/getOrderPayStatus', { orderNo: orderno })
        .then(res => {
          Loading.hide();
          if (res.data.code === '000000') {
            if (res.data.data === '0') {
              // 未支付
              reject(new Error('failed'));
            } else if (res.data.data === '1') {
              // 已支付
              resolve();
            }
          } else {
            reject(new Error('failed'));
          }
        });
    });
  },
  getIncityOrderWayPath(context, orderno) {
    return new Promise((resolve, reject) => {
      Loading.show();
      http.post('/pakj/city/getOrderWay', { orderNo: orderno }).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          context.commit('setIncityOrderWayPath', res.data.data);
          resolve();
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
          reject(new Error(res.data.code + ':' + res.data.msg));
        }
      });
    });
  }
};
const mutations = {
  resetIncity(state) {
    Object.assign(state, defaultState());
  },
  setIncityInfo(state, info) {
    if (info) {
      if (state.incityInfo) {
        if (state.incityInfo.cityId !== info.cityId) {
          state.incityInfo = info;
        }
      } else {
        state.incityInfo = info;
      }
    } else {
      state.incityInfo = info;
    }
  },
  changeIncityStatus(state, status) {
    state.incityStatus = status;
  },
  changeIncityStartPosition(state, position) {
    state.incityStartPosition = position;
  },
  changeIncityEndPosition(state, position) {
    state.incityEndPosition = position;
  },
  setDoOrderInfo(state, info) {
    if (info.length > 0) {
      info.forEach(item => {
        item.selected = false;
      });
      info[0].selected = true;
    }
    state.incityDoOrderInfo = info;
  },
  setCarSiteInfo(state, info) {
    state.carSiteInfo = info;
  },
  // 市内拼车人数
  setIncityCarpoolingNumber(state, number) {
    state.carpoolingNumber = number;
  },
  // 市内用车金额
  setIncityOrderMoney(state, info) {
    state.orderMoney = info;
  },
  // 市内用车类型
  setIncityCarType(state, info) {
    state.carType = info;
  },
  // 出租车红包
  setIncityRedMoney(state, info) {
    state.incityRedMoney = info;
  },
  // 出租车预约时间
  setIncityTime(state, info) {
    state.incityTime = info;
  },
  // 出租车出行类型
  setTaxiTravelType(state, info) {
    state.taxiTravelType = info;
  },
  setIncityCallCarInfo(state, info) {
    state.incityCallCarInfo = info;
  },
  setIncityCallCarInfoCoupon(state, coupon) {
    state.incityCallCarInfo.couponInfo = coupon;
  },
  setIncityHistoryAdress(state, list) {
    let arr = [];
    list.forEach((item, index) => {
      let obj = {
        stationName: item.address,
        position: item.address_detail,
        coordinate: decryptByDESModeEBC(item.lnglat),
        city: item.city
      };
      arr.push(obj);
    });
    state.incityHistoryAddress = arr;
  },
  setIncitySubmitPayment(state, info) {
    state.incitySubmitPaymentInfo = info;
  },
  setIncityOrderInfo(state, info) {
    state.incityOrderInfo = info;
    state.incityOrderStatus = info.orderStatus;
  },
  setIncityOrderStatus(state, status) {
    state.incityOrderInfo = status;
  },
  setIncityCityList(state, list) {
    if (list && list instanceof Array && list.length > 0) {
      let arr = list.filter(item => {
        return (
          item.serviceType.indexOf('2') >= 0 ||
          item.serviceType.indexOf('1') >= 0
        );
      });
      if (arr && arr.length > 0) {
        state.incityCityList = arr;
        state.incitySortedCityList = pySegSort(arr);
      }
    } else {
      state.incityCityList = [];
    }
  },
  setIncityOrderWayPath(state, path) {
    if (path instanceof Array) {
      if (path.length > 0) {
        path.forEach((item, index) => {
          item.lnglat = decryptByDESModeEBC(item.lnglat).split(',');
        });
      }
    }
    state.orderWayPath = path;
  }
};
const getters = {
  incityStatus(state) {
    return state.incityStatus;
  },
  incityOrderStatus(state) {
    return state.incityOrderStatus;
  },
  incityInfo(state) {
    return state.incityInfo;
  },
  incityFence(state) {
    let fences = [];
    if (state.incityInfo) {
      if (state.incityInfo.snEfnce && state.incityInfo.snEfnce !== '') {
        let arr = state.incityInfo.snEfnce.split(';');
        arr.forEach(item => {
          fences.push(item.split(','));
        });
      }
    }
    return fences;
  },
  incityFenceCenter(state) {
    let arr;
    if (state.incityInfo) {
      if (state.incityInfo.snEfncePort && state.incityInfo.snEfncePort !== '') {
        let c = state.incityInfo.snEfncePort.split(',');
        if (c.length === 2) {
          arr = c;
        }
      }
    }
    return arr;
  },
  incityHasTaxi(state) {
    if (state.incityInfo) {
      let arr = state.incityInfo.serviceType.split(',');
      return arr.indexOf('1') >= 0;
    } else {
      return false;
    }
  },
  incityStartPosition(state) {
    return state.incityStartPosition;
  },
  incityEndPosition(state) {
    return state.incityEndPosition;
  },
  incityDoOrderInfo(state) {
    return state.incityDoOrderInfo;
  },
  getCityNumberData(state) {
    return state.carSiteInfo;
  },
  getIncityCallCarData(state) {
    return state.incityCallCarInfo;
  },
  getIncityCallCarDataCoupon(state) {
    return state.incityCallCarInfo.couponInfo;
  },
  getIncityCarpoolingNumberData(state) {
    return state.carpoolingNumber;
  },
  getIncityOrderMoneyData(state) {
    return state.orderMoney;
  },
  getIncityCarTypeData(state) {
    return state.carType;
  },
  getIncityRedMoneyData(state) {
    return state.incityRedMoney;
  },
  getIncityTimeData(state) {
    return state.incityTime;
  },
  getTaxiTravelTypeData(state) {
    return state.taxiTravelType;
  },
  incityHistoryAddress(state) {
    return state.incityHistoryAddress;
  },
  getIncitySubmitPaymentDate(state) {
    return state.incitySubmitPaymentInfo;
  },
  getIncityOrderDate(state) {
    return state.incityOrderInfo;
  },
  incityCityList(state) {
    return state.incityCityList;
  },
  incitySortedCityList(state) {
    return state.incitySortedCityList;
  },
  incityDriverTopic(state) {
    return state.incityOrderInfo.gpsTopic;
  },
  incityOrderTopic(state) {
    return state.incityOrderInfo.orderTopic;
  },
  incityOrderStartPositionInfo(state) {
    let obj = {
      coordinate: decryptByDESModeEBC(state.incityOrderInfo.startLnglat).split(
        ','
      ),
      stationName: state.incityOrderInfo.startPst,
      position: state.incityOrderInfo.startPstDetail
    };
    return obj;
  },
  incityOrderEndPositionInfo(state) {
    let obj = {
      coordinate: decryptByDESModeEBC(state.incityOrderInfo.endLnglat).split(
        ','
      ),
      stationName: state.incityOrderInfo.endPst,
      position: state.incityOrderInfo.endPstDetail
    };
    return obj;
  },
  incityOrderWayPath(state) {
    return state.orderWayPath;
  },
  incityOrderMiddleWayPathCoordinate(state) {
    if (state.orderWayPath.length > 2) {
      let arr = state.orderWayPath.slice(1);
      arr.pop();
      let result = [];
      arr.forEach((item, index) => {
        result.push(item.lnglat);
      });
      return result;
    } else {
      return null;
    }
  },
  incityDriverPositionByAPI(state) {
    if (state.incityOrderInfo) {
      return decryptByDESModeEBC(state.incityOrderInfo.driverRecentLng).split(
        ','
      );
    } else {
      return null;
    }
  },
  incityOrderNearDriverFlag(state) {
    return state.incityOrderInfo.nearDriverFlag === '1';
  }
};
export default {
  state,
  actions,
  mutations,
  getters
};
